package com.wontube.smr.web.controller.admin;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wontube.client.conf.ServerEnvironment;
import com.wontube.client.extension.utils.StringUtils;
import com.wontube.client.pub.ProxyRequest;
import com.wontube.client.pub.RequestHeaders;

/**
 * @author tanggf(2012-7-4)
 *
 */
@Controller
@RequestMapping("/admin/testing")
public class AdminTestingController {
	@RequestMapping("")
	public ModelAndView testing_home(){
		return new ModelAndView("admin/testing/testing_index");
	}
	
	@RequestMapping("/requestapi")
	@ResponseBody
	public String requestapi(
			@RequestParam("serverUrl") String serverUrl,
			@RequestParam("handler") String clazzName, 
			@RequestParam("method") String methodName,
			@RequestParam("args") String[] args){
		RequestHeaders headers = new RequestHeaders();
		headers.setSessionId("");
		headers.setAgent("wontube");
		headers.setApiVersion("1.2");
		headers.setDataFormat("json");
		headers.setClazzName(clazzName);
		headers.setMethodName(methodName);
		ProxyRequest request = new ProxyRequest();
		request.setHeaders(headers);		
		if(args != null){			
			List<String> argList = new ArrayList<String>();
			for (String arg : args) {
				if( ! StringUtils.isNullOrEmpty(arg)){
					argList.add(arg);
				}
			}		
			
			if(argList.size() > 0){
				args = argList.toArray(new String[0]);
				request.setArguments(args);
			}else{
				request.setArguments(new String[0]);
			}
		}
	
		try {
			String respone = doRequest(serverUrl, request);
			return respone;
		} catch (Exception e) {
			return "error happen: " + e.getMessage();
		}
	}
	
	@RequestMapping("/test")
	@ResponseBody
	public String admin_test(HttpServletRequest request) throws IOException{
		InputStream is = request.getInputStream();
		String result = new String(readInputStream(is));
		return result;
	}
	
	private byte[] readInputStream(InputStream is) throws IOException{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] bytes = new byte[1024];
		int len = 0;
		while( (len = is.read(bytes)) > 0){
			bos.write(bytes, 0, len);
		}
		
		bos.close();
		is.close();
		return bos.toByteArray();
	}
	
	private String doRequest(String serverUrl, ProxyRequest request) throws Exception{
		URL uri = new URL(serverUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setInstanceFollowRedirects(true);				
		conn.connect();
		try {
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), ServerEnvironment.charsetName);
			try {
				String value = request.toJsonString();
				writer.write(value);
				writer.flush();	
			} finally {
				writer.close();
			}

			InputStreamReader reader = new InputStreamReader(conn.getInputStream(), ServerEnvironment.charsetName);
			StringBuilder sb = new StringBuilder();
			char[] cbuffer = new char[512];
			try {
				while (true) {
					int len = reader.read(cbuffer, 0, cbuffer.length);
					if (len <= 0) {
						break;
					}
					sb.append(cbuffer, 0, len);
				}
			} finally {
				reader.close();
			}
			return sb.toString();
		} finally {
			conn.disconnect();
		}
	}
}
